<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-steps :active="step" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="规格参数"></el-step>
          <el-step title="保存完成"></el-step>
        </el-steps>
      </el-col>
      <el-col :span="24" v-show="step==0">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-form ref="spuBaseForm" :model="spu" label-width="120px" :rules="spuBaseInfoRules">
            <el-form-item label="选择分类" prop="categoryId">
              <category-cascader></category-cascader>
            </el-form-item>
            <el-form-item label="选择课程" prop="courseId">
              <brand-select></brand-select>
            </el-form-item>
            <el-form-item label="课程描述" prop="courseDescript">
              <el-input v-model="spu.courseDescript" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="设置积分" prop="bounds">
              <label>金币</label>
              <el-input-number
                style="width:130px"
                placeholder="金币"
                v-model="spu.bounds.buyBounds"
                :min="0"
                controls-position="right"
              ></el-input-number>
              <label style="margin-left:15px">成长值</label>
              <el-input-number
                style="width:130px"
                placeholder="成长值"
                v-model="spu.bounds.growBounds"
                :min="0"
                controls-position="right"
              >
                <template slot="prepend">成长值</template>
              </el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="collectSpuBaseInfo">下一步：设置基本参数</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step==1">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <el-tabs tab-position="left" style="width:98%">
            <el-tab-pane
              :label="group.attrGroupName"
              v-for="(group,gidx) in dataResp.attrGroups"
              :key="group.attrGroupId"
            >
              <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  spu.baseAttrs[0] = [{attrId:xx,val:}]-->
              <el-form ref="form" :model="spu">
                <el-form-item
                  :label="attr.attrName"
                  v-for="(attr,aidx) in group.attrs"
                  :key="attr.attrId"
                >
                  <el-input
                    v-model="dataResp.baseAttrs[gidx][aidx].attrId"
                    type="hidden"
                    v-show="false"
                  ></el-input>
                  <el-select
                    v-model="dataResp.baseAttrs[gidx][aidx].attrValues"
                    :multiple="attr.attrType == 1"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择或输入值"
                  >
                    <el-option
                      v-for="(val,vidx) in attr.valueSelect.split(';')"
                      :key="vidx"
                      :label="val"
                      :value="val"
                    ></el-option>
                  </el-select>
                  <el-checkbox
                    v-model="dataResp.baseAttrs[gidx][aidx].quickShow"
                    :true-label="1"
                    :false-label="0"
                  >快速展示</el-checkbox>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <div style="margin:auto">
            <el-button type="primary" @click="step = 0">上一步</el-button>
            <el-button type="success" @click="generateSaleAttrs">下一步：提交数据</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step==2">
        <el-card class="box-card" style="width:80%;margin:20px auto">        
          <el-button type="primary" @click="step = 1">上一步</el-button>
          <el-button type="success" @click="submitSkus">提交数据</el-button>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step==3">
        <el-card class="box-card" style="width:80%;margin:20px auto">
          <h1>保存成功</h1>
          <el-button type="primary" @click="addAgian">继续添加</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import CategoryCascader from "../common/category-cascader";
import BrandSelect from "../common/course-select";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { CategoryCascader, BrandSelect},
  props: {},
  data() {
    return {
      catPathSub: null,
      courseIdSub: null,
      courseDescriptSub:null,
      step: 0,
      //spu_name  spu_description  catalog_id  brand_id  weight  publish_status
      spu: {
        //要提交的数据
        courseDescript: "",
        categoryId: 0,
        courseId: "",
        bounds: {
          //积分
          buyBounds: 0,
          growBounds: 0
        },
        baseAttrs: [], //基本属性
      },
      spuBaseInfoRules: {
        // spuName: [
        //   { required: true, message: "请输入商品名字", trigger: "blur" }
        // ],
        // spuDescription: [
        //   { required: true, message: "请编写一个简单描述", trigger: "blur" }
        // ],
        // categoryId: [
        //   { required: true, message: "请选择一个分类", trigger: "blur" }
        // ],
        // courseId: [
        //   { required: true, message: "请选择一个课程", trigger: "blur" }
        // ],
        // decript: [
        //   { required: true, message: "请上传商品详情图集", trigger: "blur" }
        // ],
        // images: [
        //   { required: true, message: "请上传商品图片集", trigger: "blur" }
        // ],
        // weight: [
        //   {
        //     type: "number",
        //     required: true,
        //     message: "请填写正确的重量值",
        //     trigger: "blur"
        //   }
        // ]
      },
      dataResp: {
        //后台返回的所有数据
        attrGroups: [],
        baseAttrs: [],
        steped: [false, false, false, false, false]
      }
    };
  },
  //方法集合
  methods: {
    addAgian() {
      this.step = 0;
      this.resetSpuData();
    },
    resetSpuData() {
      //重置所有信息
      this.spu = {
        courseDescript: "",
        categoryId: 0,
        courseId: "",
        bounds: {
          //积分
          buyBounds: 0,
          growBounds: 0
        },
        baseAttrs: [] //基本属性
      };
    },
    collectSpuBaseInfo() {
      //spuBaseForm  检验结果
      this.$refs.spuBaseForm.validate(valid => {
        if (valid) {
          this.step = 1;
          this.showBaseAttrs();
        } else {
          return false;
        }
      });
    },
    generateSaleAttrs() {
      //把页面绑定的所有attr处理到spu里面,这一步都要做
      this.spu.baseAttrs = [];
      this.dataResp.baseAttrs.forEach(item => {
        item.forEach(attr => {
          let { attrId, attrValues, quickShow } = attr;
          //跳过没有录入值的属性
          if (attrValues != "") {
            if (attrValues instanceof Array) {
              //多个值用;隔开
              attrValues = attrValues.join(";");
            }
            this.spu.baseAttrs.push({ attrId, attrValues, quickShow });
          }
        });
      });
      console.log("baseAttrs", this.spu.baseAttrs);
      this.step = 2;
      //--------------
    },
    showBaseAttrs() {
      //-----------------------------------
      if (!this.dataResp.steped[0]) {
        this.$http({
          url: this.$http.adornUrl(
            `/ly/attrgroup/${this.spu.categoryId}/withattr`
          ),
          method: "get",
          params: this.$http.adornParams({})
        }).then(({ data }) => {
          //先对表单的baseAttrs进行初始化
          data.data.forEach(item => {
            let attrArray = [];
            item.attrs.forEach(attr => {
              attrArray.push({
                attrId: attr.attrId,
                attrValues: "",
                quickShow: attr.quickShow
              });
            });
            this.dataResp.baseAttrs.push(attrArray);
          });
          this.dataResp.steped[0] = 0;
          this.dataResp.attrGroups = data.data;
        });
      }
    },

    submitSkus() {
      console.log("~~~~~", JSON.stringify(this.spu));
      this.$confirm("将要提交商品数据，需要一小段时间，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/ly/classcourseattrvalues/save/baseAttrsValues"),
            method: "post",
            data: this.$http.adornData(this.spu, false)
          }).then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                type: "success",
                message: "新增课程属性成功!"
              });
              this.step = 3;
            } else {
              this.$message({
                type: "error",
                message: "保存失败，原因【" + data.msg + "】"
              });
            }
          });
        })
        .catch(e => {
          console.log(e);
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.catPathSub = PubSub.subscribe("catPath", (msg, val) => {
      this.spu.categoryId = val[val.length - 1];
    });
    this.courseIdSub = PubSub.subscribe("courseId", (msg, val) => {
      this.spu.courseId = val;
    });
    this.courseDescriptSub = PubSub.subscribe("courseDescript", (msg, val) => {
      this.spu.courseDescript = val;
    });
    // this.getMemberLevels();
  },
  beforeDestroy() {
    PubSub.unsubscribe(this.catPathSub);
    PubSub.unsubscribe(this.courseIdSub);
    PubSub.unsubscribe(this.courseDescriptSub);
  } //生命周期 - 销毁之前
};
</script>
<style scoped>
</style>